package com.t.bricks.bussiness.service.msgagent.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.t.bricks.bussiness.model.msgagent.SendMsg;
import com.t.bricks.bussiness.service.msgagent.MsgAgentService;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.utils.function.json.JacksonShell;
import com.t.bricks.utils.function.url.URLUtil;

/**
 * 消息转发业务处理
 */
@Service
public class MsgAgentServiceImpl implements MsgAgentService {
	
	/**
	 * 微信后台接收消息的url配置
	 */
	@Value("${app.wechat.push.msg.url:微信后台接收消息的url未进行配置}")//http://localhost:8024/wechat/push/msg
	private String wechatPushMsgUrl;

	/**
	 * 消息转发
	 * @param sendMsg
	 * @return
	 */
	@Override
	public MsgEmity agent(SendMsg sendMsg) {
		if (null == wechatPushMsgUrl || "".equals(wechatPushMsgUrl.trim()) || "微信后台接收消息的url未进行配置".equals(wechatPushMsgUrl)) {
			return MsgEmity.err(8000, "微信后台接收消息的url配置'app.wechat.push.msg.url'未进行配置");
		}
		
		if (null == sendMsg) {
			return MsgEmity.err(8001, "信息对象参数为空");
		}
		
		if (null == sendMsg.getsRecipientsId() || "".equals(sendMsg.getsRecipientsId().trim())) {
			return MsgEmity.err(8002, "接收人编号不能为空");
		}
		
		if (null == sendMsg.getsRecipientsName() || "".equals(sendMsg.getsRecipientsName().trim())) {
			return MsgEmity.err(8003, "接收人关注号不能为空");
		}
		
		if (null == sendMsg.getsSpokesman() || "".equals(sendMsg.getsSpokesman().trim())) {
			return MsgEmity.err(8004, "发送人不能为空");
		}
		
		if (null == sendMsg.getsTitle() || "".equals(sendMsg.getsTitle().trim())) {
			return MsgEmity.err(8005, "消息标题不能为空");
		}
		
		if (null == sendMsg.getsMsg() || "".equals(sendMsg.getsMsg().trim())) {
			return MsgEmity.err(8006, "消息内容不能为空");
		}
		
		String parameJson = JacksonShell.toJSONString(sendMsg);
		MsgEmity me = URLUtil.postJson(wechatPushMsgUrl, parameJson);
		if (null == me) {
			return MsgEmity.err(8007, "访问'", wechatPushMsgUrl, "'失败,返回未定义的结果:NULL");
		}
		
		if (!me.isSuccess()) {
			return me.setData((Integer)me.getData() + 1000);
		}
		
		me = JacksonShell.toJavaObject(me.getData(), MsgEmity.class);
		if (null == me) {
			return MsgEmity.err(8008, "访问'", wechatPushMsgUrl, "'的结果值转换对象失败,转换结果为:NULL");
		}
		
		if (!me.isSuccess()) {
			return me.setData((Integer)me.getData() + 2000);
		}
	
		return me;
	}

}
